package com.bah.tract.client.workstore.tol;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.bah.tract.client.workstore.TaskProvider;
import com.bah.tract.service.BooleanProperty;
import com.bah.tract.service.StringProperty;
import com.bah.tract.service.Task;

@Singleton
public class TOLTaskProvider implements TaskProvider, TaxLocationProvider {

	private final TOLData data;

	private String defaultTaxCode;

	@Inject
	TOLTaskProvider(final TOLClient client, final TOLResponseParser parser,
			final Preferences preferences) throws IOException {
		// Just read everything once at startup
		defaultTaxCode = preferences.get("taxCode", "VAAL");
		preferences.addPreferenceChangeListener(new PreferenceChangeListener() {

			@Override
			public final void preferenceChange(final PreferenceChangeEvent evt) {
				if ("taxCode".equals(evt.getKey())) {
					defaultTaxCode = evt.getNewValue();
				}
			}
		});
		final ByteArrayOutputStream bos = new ByteArrayOutputStream();
		client.requestForm(bos);
		data = parser
				.parseResponse(new ByteArrayInputStream(bos.toByteArray()));
	}

	@Override
	public List<Task> getTasks() {
		// Create a new list each time so that users can change taxcode, and
		// telework options
		final List<Task> tasks = new ArrayList<Task>();
		for (final Map.Entry<String, String> entry : data.getChargeNumbers()
				.entrySet()) {
			final Task task = new Task();
			task.setStoreId(1);
			task.setType("ChargeNumber");
			task.setDescription(entry.getKey());
			task.setLabel(entry.getValue());
			task.getIdentifyingProperty().add(
					new StringProperty("number", entry.getValue()));
			final StringProperty taxCode = new StringProperty("taxCode",
					defaultTaxCode);
			task.getIdentifyingProperty().add(taxCode);
			final BooleanProperty telework = new BooleanProperty("teleWork",
					false);
			task.getIdentifyingProperty().add(telework);
			tasks.add(task);
		}
		return tasks;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.bah.tract.client.workstore.tol.TaxLocationProvider#getTaxLocations()
	 */
	@Override
	public Map<String, String> getTaxLocations() {
		return data.getTaxLocations();
	}

}
